package com.wuliang.generate.common.sharding.factories;

import com.wuliang.generate.common.sharding.domain.Sharding;
import com.wuliang.generate.common.sharding.pool.DefaultShardingDataSourcePool;

import java.util.List;
import java.util.Map;

public class ShardingDataSourceBuilder {

    public static ShardingBuilder createBuilderByKeyword(String keyword) {
        return new ShardingBuilder(keyword);
    }

    public static ShardingBuilder createBuilder() {
        return new ShardingBuilder();
    }

    public static class ShardingBuilder {
        private String url;
        private String keyword;
        private String username;
        private String password;
        private List<String> tableNamesInDatabase;
        private Map<String, List<String>> columnsWithTableLink;

        public ShardingBuilder() {
        }

        public ShardingBuilder(String keyword) {
            this.keyword = keyword;
        }

        public ShardingBuilder url(String url) {
            this.url = url;
            return this;
        }

        public ShardingBuilder keyword(String keyword) {
            this.keyword = keyword;
            return this;
        }

        public ShardingBuilder username(String username) {
            this.username = username;
            return this;
        }

        public ShardingBuilder password(String password) {
            this.password = password;
            return this;
        }

        public ShardingBuilder tableNamesInDatabase(List<String> tableNamesInDatabase) {
            this.tableNamesInDatabase = tableNamesInDatabase;
            return this;
        }

        public ShardingBuilder columnsWithTableLink(Map<String, List<String>> columnsWithTableLink) {
            this.columnsWithTableLink = columnsWithTableLink;
            return this;
        }

        public Sharding build() {
            Sharding sharding = new Sharding();
            sharding.setUrl(url);
            sharding.setDatabaseName(getDatabaseName());
            sharding.setUsername(username);
            sharding.setPassword(password);
            sharding.setTableNamesInDatabase(tableNamesInDatabase);
            sharding.setColumnsWithTableLink(columnsWithTableLink);
            DefaultShardingDataSourcePool.SHARDING_LIST.put(keyword, sharding);
            return sharding;
        }

        private String getDatabaseName() {
            String[] jdbcUrlOfShards = url.split("/");
            return jdbcUrlOfShards[jdbcUrlOfShards.length - 1].substring(0, jdbcUrlOfShards[jdbcUrlOfShards.length - 1].indexOf('?'));
        }
    }
}
